//
//  WGApiService.m
//  WorkGo
//
//  Created by 李树志 on 2017/9/30.
//  Copyright © 2017年 李树志. All rights reserved.
//

#import "WGApiService.h"
#import "WGDay.h"

@interface WGApiService()
{
    NSString *_URLString;
}

@end

@implementation WGApiService

- (instancetype)init
{
    self = [super init];
    if (self) {
//        NSDate *date = [NSDate date];
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        formatter.dateFormat = @"yyyy-MM-dd";
//        NSString *dateString = [formatter stringFromDate:date];
//        _URLString = [NSString stringWithFormat:@"https://apicloud.mob.com/appstore/calendar/day?key=moba6b6c6d6&date=%@", dateString];
    }
    return self;
}

+ (instancetype)sharedService {
    static WGApiService *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[WGApiService alloc] init];
    });
    return _instance;
}

- (void)setCurrentDate:(NSString *)currentDate
{
    _currentDate = currentDate;
    _URLString = [NSString stringWithFormat:@"https://apicloud.mob.com/appstore/calendar/day?key=moba6b6c6d6&date=%@", currentDate];
}

- (void)sendCalendarRequest:(void (^)(WGDay *, NSError *))resultHandler
{
    // 1.创建一个网络URL
    NSURL *url = [NSURL URLWithString:_URLString];
    // 2.创建一个网络请求
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    // 3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    // 4.根据会话对象,创建一个Task任务
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSInteger status = [dict[@"retCode"] integerValue];
        if (status == 200) {
//            NSLog(@"%@", dict);
            if (resultHandler) {
                NSDictionary *resultDict = dict[@"result"];
                WGDay *day = [WGDay dayWithDict:resultDict];
                resultHandler(day, nil);
            }
        } else {
            NSLog(@"%@", dict);
            if (resultHandler)
            {
                resultHandler(nil, error);
            }
        }
    }];
    // 5.最后一步,执行任务(resume也是继续执行)
    [sessionDataTask resume];
}

@end
